<?php
namespace App\Models;

use Awobaz\Compoships\Compoships;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Contract extends BaseModel
{

//    use Compoships;
    protected $table = 'yt_contract';
    public $timestamps = false;

    protected $fillable = [
        'invoice_type',
        'contract_no',
        'contract_date',
        'seller_id',
        'buyer_id',
        'currency',
        'trade_terms',
        'payment_type',  //付款条件
        'harb_from',  // 起运港/装运地POL
        'harb_dest',  // 目标地/卸货地POD
        'from_area',
        'dest_area',
//        'category',
        'date',  //发票日期 (离场日期)
        'boat_date',
        'agent_fee', //代理支付费用
        'transport_type',
        'bill_no',
        'bill_no_file',
        'cabinet_no',
        'seal',
        'logistics',
        'port_fee',
        'transport_fee',
        'customs_no',
        'customs_no_file',
        'exporter_date',
        'pass_file',
        'status',
        'delivery_external_no'
    ];


//    public $cats = [
//        'customs_no_file' => 'array'
//    ];

    // 运输方式
    const TransportType = [
        'FCL' => '海运(FCL)',
        'LCL' => '海运(LCL)',
        'AIR' => '空运(AIR)',
        'EXP' => '空运(EXP)',
    ];


    // 付款条件
    const PaymentType = [
        'T/T before Shippment' => 'T/T before Shippment',
        '30 Days after Received' => '30 Days after Received',
        'T/T 30 Days' => 'T/T 30 Days',

    ];

//    // 开票类型
//    const InvoiceType = [
//        'A' => '1张发票对应1张关单',
//        'B' => '1张发票对多张关单',
//    ];

    // 开票类型
    const InvoiceType = [
        'A' => 'A',
        'B' => 'B',
        'A-1' => 'A-1',
        'A-2' => 'A-2',
        'B-1' => 'B-1',
        'B-2' => 'B-2',
        'C' => 'C',
        'D' => 'D'
    ];

    // 贸易条款
    const TradeTerms = [
        'FOB' => 'FOB',
        'CIF' => 'CIF',
    ];


    const Currency = [
        'USD' => '美元',
        'AUD' => '澳元',
        'GBP' => '英镑',
        'EUR' => '欧元',
        'CAD' => '加元',
        'MXN' => '墨西哥比索',
        'RMB' => '人民币',
        'SEK' => '瑞典克朗',
    ];

    const CONTRACT_STATUS_MAP = [
        '0' => '未报关',
        '1' => '已报关',
        '2' => '已回传',
        '3' => '已开票'
    ];

    const CONTRACT_STATUS = [
        'CUSTOMS'  => 0,
        'CUSTOMED' => 1,
        'RETURN'   => 2,
        'INVOICED' => 3
    ];


    protected $month = [
        '01' => 'Jan.',
        '02' => 'Feb.',
        '03' => 'Mar.',
        '04' => 'Apr.',
        '05' => 'May',
        '06' => 'Jun.',
        '07' => 'Jul.',
        '08' => 'Aug.',
        '09' => 'Sept.',
        '10' => 'Oct.',
        '11' => 'Nov.',
        '12' => 'Dec.',
    ];
    const DELAYDAY = 7;



    public function cates(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(CustomsCates::class, 'cid');
    }

    public function buyer(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(CustomsExporter::class, 'buyer_id');
    }

    public function harb()
    {
        return $this->belongsTo(CustomsHarbour::class, 'harb_dest');
    }

    public function getBoatDateEnAttribute(): string
    {
        $date = (new Carbon($this->attributes['boat_date']))->format('m-d-Y');
        $dateArray = explode('-', $date);
        return $this->month[$dateArray[0]].' '.$dateArray[1].', '.$dateArray[2];
    }

    public function getSellerAttribute()
    {
        $seller = CustomsExporter::query()->select(['name_cn', 'name_en', 'addr'])->find($this->seller_id);
        $seller->addr = explode(' ', $seller->addr);
        $data = [];
        foreach ($seller->addr as $key => $addr) {
            if ($key > 9) {
                $data['down'][] = $addr;
            } else {
                $data['up'][] = $addr;
            }
        }
        $seller->addr = $data;
        return $seller;
    }


    public static function getInfoByContractNo($no)
    {
        return Cache::Remember('getContractInfoByNo.' .  $no, config('constants.LITTLE_CACHE_EXPIRES'), function () use ($no) {
            $info = self::where(['contract_no' => $no])->first(['id', 'contract_no', 'currency', 'exporter_date', 'contract_date','status']);

            return $info;
        });
    }


    // 获得装运日期
    static function makeBoatDate($date, $fmt='Y-m-d')
    {
        return \Carbon\Carbon::parse($date)->addDays(14)->format($fmt);
    }

    protected static function booted()
    {
        static::deleting(function ($data) {
            if ($data->is_imported == 1) {
                throw new \Exception("无法删除");
            }
            return true;
        });
    }



    public function refundCheck(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(CustomsRefundTax::class, 'cid');
    }

//    public function billNo()
//    {
//        return $this->hasOne(ContractBill::class, 'contract_no','contract_no');
//    }


  /*  public function setCustomsNoFileAttribute($val)
    {
        if (is_array($val)) {
            $this->attributes['customs_no_file'] = json_encode($val);
        }
    }*/

//    public function getCustomsNoFileAttribute($val)
//    {
//        return json_decode($val, true);
//    }


    public static function getContractDate($date)
    {
        return Cache::Remember('getDelayDate.' .  $date, config('constants.LITTLE_CACHE_EXPIRES'), function () use ($date) {
            $days = 0;
            $holiday = HolidayCn::getHolidayList();
            $workDay = HolidayCn::getWorkDays();
            $i = 1;
            do {
                $dateTime = Carbon::create($date)->addDays($i);

                //如果是周末
                if ($dateTime->isWeekend()) {
                    //如果周末上班时间
                    if (isset($workDay[$dateTime->format('Y-m-d')])) {
                        $days += 1;
                    }
                } elseif (!isset($holiday[$dateTime->format('Y-m-d')])) {
                    $days += 1;
                }
                $i ++;
            } while ($days < self::DELAYDAY);
            return $dateTime->format('Y-m-d');
        });

    }
}
